import json
import random

import requests
# 导入缓存cache模块
from django.core.cache import cache
from django.http import JsonResponse
from rest_framework import viewsets, mixins
from rest_framework.decorators import list_route, api_view
from rest_framework.response import Response

# from orders.models import OrderModel
from users.models import UserModel
from users.serializer import UserSerializer, ChangeInfoSerializer, RegisterSerializer, LoginSeriaqlizer, ChangeSerializer
from utils.authentication import UserAuthentication
from utils.errors import ParamsException


class UserView(viewsets.GenericViewSet,
               mixins.ListModelMixin,
               ):
    # xx 就是继承ListModelMixin，RetrieveModelMixin等

    # 资源数据
    queryset = UserModel.objects.all()
    # 序列化
    serializer_class = UserSerializer
    #  认证类
    authentication_classes = (UserAuthentication,)

    # 展示个人中心信息
    def list(self, request, *args, **kwargs):
        token = request.GET.get('token')
        user_tel = cache.get(token)
        user = UserModel.objects.filter(user_tel=user_tel).first()
        if not user:
            raise ParamsException({
                'code': 1009,
                'msg': '请先请登录',
            })
        # 序列化所有字段
        serializer = self.get_serializer(user)
        res = {
            'user_info': serializer.data
        }
        return Response(res)

    # 修改个人中心信息
    @list_route(methods=['POST'], serializer_class=ChangeInfoSerializer)
    def changeinfopassword(self, request):
        serializer = self.get_serializer(data=request.data)
        user = request.user
        # 没有前端页面cookie，所以先这样匹配user实例
        user = UserModel.objects.filter(user_tel=18100820320).first()
        serializer.is_valid(raise_exception=True)
        if not user:
            raise ParamsException({
                'code': 1005,
                'msg': '修改失败,请登录',
            })
        user_name = request.data.get('user_name')
        user_real_name = request.data.get('user_real_name')
        email = request.data.get('email')
        id_card_num = request.data.get('id_card_num')
        sex = request.data.get('sex')
        ctrip_account = request.data.get('ctrip_account')
        ctrip_password = request.data.get('ctrip_password')
        if user_name:
            user.user_name = user_name
        if user_real_name:
            user.user_real_name = user_real_name
        if email:
            user.email = email
        if id_card_num:
            user.id_card_num = id_card_num
        if sex:
            user.sex = sex
        if ctrip_account:
            user.ctrip_account = ctrip_account
        if ctrip_password:
            user.ctrip_password = ctrip_password
        user.save()
        res = {
            'msg': '信息修改成功'
        }
        return Response(res)


    # 修改密码
    @list_route(methods=['POST'], serializer_class=ChangeSerializer)
    def changepassword(self, request):
        serializer = self.get_serializer(data=request.data)
        user = request.user
        newpassword = request.data.get('newpassword')
        if not user:
            raise ParamsException({
                'code': 1005,
                'msg': '修改密码失败,请登录',
            })
        serializer.is_valid(raise_exception=True)
        user.password = newpassword
        user.save()
        res = {
            'msg': '修改密码成功'
        }
        return Response(res)

    @list_route(methods=['POST'], serializer_class=LoginSeriaqlizer)
    def login(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 如果执行一下的代码，就代表账号和密码没问题
        token = serializer.login_user(serializer.data)
        result = {
                'token': token,
        }
        return Response(result)

    # 装饰器
    @list_route(methods=['POST'], serializer_class=RegisterSerializer)
    def register(self, request):
        # 该方法要被调用，请求地址为： api/users/register/
        serializer = self.get_serializer(data=request.data)
        result = serializer.is_valid(raise_exception=False)
        # 判断校验结构
        if not result:
            error = serializer.errors
            raise ParamsException({
                                    'code': 1005,
                                    'msg': '注册字段有误',
                                    'data': error
                                    })
        # 校验字段没问题，且账号和密码也没问题
        user = serializer.save()
        result = {
            'data': {
                'user_id': user[0].user_id,
                'user_tel': user[0].user_tel,
                'user_name': user[0].user_name,
                'code': user[1]
            }
        }
        return Response(result)

    @list_route(methods=['GET', 'POST'])
    def send_message(self, request):
        tel = request.POST.get('user_tel')
        # 生成手机验证码字符串
        code = ''.join(random.choices('0123456789', k=6))
        cache.set(tel, code, 600)  # 600s有效期
        url = "http://v.juhe.cn/sms/send"
        params = {
            "mobile": tel,  # 接受短信的用户手机号码
            "tpl_id": "178339",  # 您申请的短信模板ID，根据实际情况修改
            "tpl_value": "#code#=" + code,  # 您设置的模板变量，根据实际情况修改
            "key": "8b1264245c552a7a9c270a517d8605c2",  # 应用APPKEY(应用详细页查询)
        }
        f = requests.post(url=url, params=params)
        resp = json.loads(f.text)
        if resp:
            print(resp)
            res = {
                'msg': resp['reason']
            }
            return Response(res)
        else:
            print("请求异常")
            res = {
                'msg': resp.reason
            }
            return Response(res)


